package com.bwie.filter;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author :Beyond🎸🎸
 * @date : 2025-10-16 16:41:16
 * @description 网关过滤器
 **/
@Component
public class GlobalFiter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpResponse response = exchange.getResponse();

        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
//1、校验是不是白名单 是就直接放行
        if(path.contains("login")){
            System.out.println(path+"请求为白名单~~不用管");
            return chain.filter(exchange);
        }
//      校验请求是否存在token
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            System.out.println(path+"请求token为空已拦截");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//      3、校验token是否过期、一致
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);

        String redisToken = redisTemplate.opsForValue().get("token-" + userId);

        if(redisToken==null){
            System.out.println("token过期！！已拦截");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//
        if(!token.equals(redisToken)){
            System.out.println("传入和缓存token不一致！！已拦截");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        4、token续期
        redisTemplate.expire("token-" + userId,60, TimeUnit.MINUTES);
//        5、放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
